package Concurent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.*;


/**
 * Created by root on 17-6-7.
 */

public class ConcurrentDemo1 {
    public static void main(String[] args)throws Exception{
       // BlockingQueue<String> queue = new ArrayBlockingQueue(5); //用数组做队列，必须指定大小
        BlockingQueue<String> queue = new LinkedBlockingQueue<>();   //链表做队列，最大长度为int的最大值，可以看成无限制大小
//        queue.add("aaa");
//        queue.add("bbb");
//        queue.add("ccc");
//        queue.add("ddd");
//        queue.add("eee");
//        //下面是失败的例子，因为之前给定了5个单位
//        queue.offer("fff",3,TimeUnit.SECONDS);   //阻塞3秒
//        //queue.add("fff");       //这个是返回队列空的异常
//       // queue.offer("fff");       //返回布尔型
//        //queue.offer("fff");    //一直阻塞
        new Thread(new T1(queue)).start();
        new Thread(new T2(queue)).start();
    }
}

class T2 implements Runnable{
    private BlockingQueue<String> queue = null;

    public T2 (BlockingQueue<String> queue){
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            for(int i=0;i<Integer.MAX_VALUE;i++){
                String str = queue.take();
                System.out.println("消费者消费了"+str);

                Thread.sleep(3000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

class T1 implements Runnable{
    private BlockingQueue<String> queue = null;

    public T1 (BlockingQueue<String> queue){
        this.queue = queue;
    }


    @Override
    public void run() {
        try {
        for(int i=0;i<Integer.MAX_VALUE;i++){
            String str = "x"+i;
            queue.put(str);
            System.out.println("生产者生产了"+str);
            Thread.sleep(2000);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}